<?php
class OnlineUsers{
 
	protected $ip = '';
 
	protected $time = null;

	protected $timeout = 360;

	protected $link = null;

	protected $stmt = null;
	
	private	$ci = null;
	private 	$table = 'online_users';

	function __construct (){
		session_start();
		$this->session_id = session_id();
		$this->ip	=	$_SERVER['REMOTE_ADDR'];
		$this->time = time();
		$this->ci = &get_instance();
		if(!$this->ci->db->table_exists($this->table))
			$this->install();
		$this->delete_update_onlineusers();
		$this->insert_onlineusers();
	}
	
	private function install(){
		$sql = "CREATE TABLE IF NOT EXISTS `".$this->table."` (
				`session_id` CHAR(150) NOT NULL,
				`ip` VARCHAR(15) NULL DEFAULT NULL,
				`last_activity` INT(11) NULL DEFAULT NULL,				
				PRIMARY KEY (`session_id`)
			)
			COLLATE='utf8_general_ci'
			ENGINE=InnoDB;";
		$this->ci->db->query($sql);
	}
	
	/**
	* Gets current online users
	*/
	function get_online_users (){
	  $this->delete_update_onlineusers();
	  $this->insert_onlineusers();
	  $timeout = time() - ($this->timeout * 60);
	  return $this->ci->db->query("SELECT COUNT(*) online FROM online_users WHERE last_activity >= $timeout")->row()->online;
	}

	private function already_registred (){
	  $aday = $this->time - (24 * 60 * 60);
	  $result = $this->ci->db->query("SELECT session_id FROM {$this->table} WHERE ip='{$this->ip}'
	   AND last_activity >= $aday");
	  if(!count($result->result()))
			return false;
	  return true;
	}

	private function insert_onlineusers(){
		if (!$this->already_registred())
			$this->ci->db->query("INSERT INTO {$this->table} VALUES('{$this->session_id}','{$this->ip}',$this->time)");
	}

	private function delete_update_onlineusers()	{
		$timeout = $this->time - ($this->timeout * 60);
		// $aday = $this->time - (24*60*60);
		// $this->ci->db->query("DELETE FROM online_users WHERE last_activity<=$timeout");
		$this->ci->db->query("UPDATE {$this->table} SET last_activity={$this->time} 
										WHERE session_id='{$this->session_id}'");
	}

	/**
	* Set timeout in minutes.
	* 
	* @param int $timeout            
	*/
	function set_timeout ($timeout){
	  $this->timeout = ((int) $timeout);
	}
	
	function get_statistic(){
		$online_timeout = time() - ($this->timeout * 60);
		$today_timeout = strtotime(date('Y-m-d') . " 00:00:00");
		$month_timeout = strtotime(date('Y-m-01') . " 00:00:00");
		$sql = " * FROM
		(
			(SELECT count(*) online FROM (`{$this->table}`) WHERE `last_activity` >= $online_timeout) online,
			(SELECT count(*) today FROM (`{$this->table}`) WHERE `last_activity` >= $today_timeout) today,
			(SELECT count(*) month FROM (`{$this->table}`) WHERE `last_activity` >= $month_timeout) month,
			(SELECT count(*) total FROM (`{$this->table}`) ) total
		)";
		$this->ci->db->select($sql,false,false);
		return $this->ci->db->get()->row();
	}
}
 
?>